package com.tywj.lib.lifecycle.livedata

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.tywj.lib.core.widget.recycleview.adapter.BaseAdapter


/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/13
 *     desc   : 集合元素变化观察者
 *     version: 1.0.0
 * </pre>
 */
class ListChangedObserver<T>(
    lifecycleOwner: LifecycleOwner,
    adapter: BaseAdapter<T>,
    liveData: ArrayListLiveData<T>
) {

    init {
        liveData.observe(lifecycleOwner, Observer {
            when (it!!.type) {
                ListChanged.TYPE_CHANGED -> {
                    adapter.notifyDataSetChanged()
                }
                ListChanged.TYPE_ITEM_RANGE_CHANGED -> {
                    adapter.notifyItemRangeChanged(
                        it.positionStart
                                + adapter.headerLayoutCount, it.itemCount
                    )
                }
                ListChanged.TYPE_ITEM_RANGE_INSERTED -> {
                    adapter.notifyItemRangeInserted(
                        it.positionStart
                                + adapter.headerLayoutCount, it.itemCount
                    )
                }
                ListChanged.TYPE_ITEM_MOVE -> {
                    adapter.notifyItemMoved(
                        it.fromPosition + adapter.headerLayoutCount
                        , it.toPosition + adapter.headerLayoutCount
                    )
                }
                ListChanged.TYPE_ITEM_RANGE_REMOVED -> {
                    adapter.notifyItemRangeRemoved(
                        it.positionStart
                                + adapter.headerLayoutCount, it.itemCount
                    )
                }
            }
        })
    }
}